import { useEffect } from "react";
import { updateField } from "../context/metadata-context";
import eventBus, { useSubscribe } from "../eventBus";
import { v4 as uuid } from "uuid";
//表单字段生命周期管理
export default function (metadataManager, field, updater) {
  //字段刷新监听生命周期
  /**
   * 更新字段数据，消息字符串格式如下：
   * 主表：updateField + `form.form_data.main.${fieldCode}`
   * 子表：updateField + `form.form_data.children.${groupCode}[${rowIndex}].${fieldCode}`;
  */
  useSubscribe(updateField + field, (value) => {
    updater({ current: true, uuid: uuid(),value });
  },[field]);
  //字段表单错误销毁生命周期
  useEffect(function () {
    
    return function () {

      // eventBus.publish("field.blur",field)
      //组件销毁的时候清除表单错误
      if (metadataManager.validationLocker !== true)
        try {
          // delete metadataManager[`property.${field}`]; //fixme:对象形式清除
          if (metadataManager.property.hasError) {
            delete metadataManager.property.hasError[`${field}`];
          }
        } catch (err) {}
    };
  }, [field]);
}
